'''
copyright: Copyright (C) 2015-2024, Wazuh Inc.

           Created by Wazuh, Inc. <info@wazuh.com>.

           This program is free software; you can redistribute it and/or modify it under the terms of GPLv2

type: integration

brief: Wazuh is able to detect vulnerabilities in the applications installed in agents using the Vulnerability Detector
       module. This software audit is performed through the integration of vulnerability feeds indexed by Redhat,
       Canonical, Debian, Amazon Linux and NVD Database.

components:
    - vulnerability_detector

suite: scan_results

targets:
    - manager

daemons:
    - wazuh-modulesd

os_platform:
    - linux

os_version:
    - Arch Linux
    - Amazon Linux 2022
    - Amazon Linux 2
    - Amazon Linux 1
    - CentOS 8
    - CentOS 7
    - Debian Buster
    - Red Hat 8
    - Ubuntu Focal
    - Ubuntu Bionic
    - Ubuntu Jammy
    - Suse Enterprise Linux Server 15
    - Suse Enterprise Linux Server 12
    - Suse Enterprise Linux Server 11
    - Suse Enterprise Linux Desktop 15
    - Suse Enterprise Linux Desktop 12
    - Suse Enterprise Linux Desktop 11

references:
    - https://documentation.wazuh.com/current/user-manual/capabilities/vulnerability-detection/index.html

tags:
    - vulnerability_detector
    - scan_results
'''
import pytest
from pathlib import Path

from .utils import update_feed_path_configurations
from wazuh_testing import FEEDS_PATH
from wazuh_testing.constants.daemons import ANALYSISD_DAEMON, MODULES_DAEMON, SYSCHECK_DAEMON
from wazuh_testing.utils.file import read_yaml
from wazuh_testing.utils.configuration import get_test_cases_data
from wazuh_testing.modules.modulesd.vulnerability_detector import patterns as cb
from wazuh_testing.modules.modulesd.configuration import MODULESD_DEBUG
from wazuh_testing.modules.monitord.configuration import MONITORD_ROTATE_LOG
from wazuh_testing.utils.mocking import VULNERABLE_PACKAGES
from test_vulnerability_detector import utils as ev
from . import TEST_CASES_PATH, CONFIGURATIONS_PATH


pytest.skip("The tests will be deprecated, they test the old Vulnerability Detector.", allow_module_level=True)

# Variables
local_internal_options = {MODULESD_DEBUG: '2', MONITORD_ROTATE_LOG: '0'}
daemons_handler_configuration = {'daemons': [ANALYSISD_DAEMON, MODULES_DAEMON, SYSCHECK_DAEMON]}
pytestmark = [pytest.mark.server]

# Configuration and cases data
configurations_path = Path(CONFIGURATIONS_PATH, 'configuration_scan_provider_and_nvd_vulnerabilities.yaml')
cases_path = Path(TEST_CASES_PATH, 'cases_scan_provider_and_nvd_vulnerabilities.yaml')

# Test configurations
test_configurations = read_yaml(configurations_path)
configuration_parameters, configuration_metadata, case_ids = get_test_cases_data(cases_path)
test_configurations = update_feed_path_configurations(test_configurations, configuration_metadata, FEEDS_PATH)
systems = [metadata['system'] for metadata in configuration_metadata]


@pytest.mark.tier(level=1)
@pytest.mark.parametrize('test_configuration, test_metadata, agent_system',
                         zip(test_configurations, configuration_metadata, systems), ids=case_ids)
def test_scan_provider_and_nvd_vulnerabilities(test_configuration, test_metadata, agent_system, set_wazuh_configuration,
                                               configure_local_internal_options, truncate_monitored_files,
                                               clean_cve_tables, prepare_full_scan_with_vuln_packages,
                                               daemons_handler):
    '''
    description: Check if the vulnerability alerts are reported from NVD and OVAL feed sources.

    test_phases:
        - setup:
            - Set a custom Wazuh configuration.
            - Mock an agent.
            - Clean CVE table.
            - Force a full scan.
            - Restart wazuh-modulesd.
        - test:
            - Check that the vulnerabilities have been detected for all packages using NVD and OVAL source.
            - Check that the vulnerabilities have been reported in the log for all packages using NVD and OVAL source.
            - Check that vulnerability alerts have been generated for all packages.
        - teardown:
            - Restart initial wazuh configuration.
            - Clean CVE table.

    wazuh_min_version: 4.4.0

    tier: 1

    parameters:
        - test_configuration:
            type: dict
            brief: Wazuh configuration data. Needed for set_wazuh_configuration fixture.
        - test_metadata:
            type: dict
            brief: Wazuh configuration metadata
        - agent_system:
             type: str
             brief: System to set to the mocked agent.
        - set_wazuh_configuration:
            type: fixture
            brief: Set the wazuh configuration according to the configuration data.
        - configure_local_internal_options:
            type: fixture
            brief: Set local_internal_options configuration.
        - truncate_monitored_files:
            type: fixture
            brief: Truncate all the log files and json alerts files before and after the test execution.
        - clean_cve_tables:
            type: fixture
            brief: Clean all CVE tables.
        - prepare_full_scan_with_vuln_packages:
            type: fixture
            brief: Setup the initial test state.
        - daemons_handler:
            type: fixture
            brief: Restart the wazuh-modulesd daemon.

    assertions:
        - Verify that the log vulnerability report appears in ossec.log for each vulnerable package.
        - Verify that the alert vulnerability report appears in alerts.json for each vulnerable package.

    input_description:
        - The `scan_nvd_vulnerabilities.yaml` file provides the module configuration for this test.
        - The `cases_scan_nvd_vulnerabilities.yaml` file provides the test cases.

    expected_output:
        - f"The '{package}' package .* from agent '{agent_id}' is vulnerable to '{cve}'"
        - f".*"agent":."id":"{agent_id}".*{cve} affects {package}"
    '''
    agent_id = prepare_full_scan_with_vuln_packages

    # Check potential vulnerabilities using the OVAL feed
    log_present = ev.check_event(cb.OVAL_POTENTIAL_VULNS, replacement={"vuln_number": "5", "agent_id": agent_id})
    assert log_present, f"OVAL feed did not detect any vulnerability for agent {agent_id}"

    # Check potential vulnerabilities using the NVD feed
    log_present = ev.check_event(cb.NVD_POTENTIAL_VULNS, replacement={"vuln_number": "5", "agent_id": agent_id})
    assert log_present, f"NVD feed did not detect any vulnerability for agent {agent_id}"

    # Check reported vulnerabilities in log using the OVAL feed
    log_present = ev.check_event(cb.TOTAL_VULN_REPORTED,
                                 replacement={"vuln_number": "5", "agent_id": agent_id, "feed": "vendor"})
    assert log_present, f"OVAL feed did not report the expected vulnerabilities for agent {agent_id}"

    # Check reported vulnerabilities in log using the NVD feed
    log_present = ev.check_event(cb.TOTAL_VULN_REPORTED,
                                 replacement={"vuln_number": "5", "agent_id": agent_id, "feed": "NVD"})
    assert log_present, f"NVD feed did not report the expected vulnerabilities for agent {agent_id}"

    # Check the vulnerabilities alerts
    for package in VULNERABLE_PACKAGES:
        log_present = ev.check_cve_affects_package_alert(agent_id, package['name'], package['cveid'])
        assert log_present is not None, f"Expected '{package['cveid']} affects {package['name']}' alert not found"
